import React, { useState } from 'react';
import styled from 'styled-components';
import { Button, Tabs, message, Modal, Drawer } from 'antd';
import { BookOutlined } from '@ant-design/icons';
import ToolBar from './ToolBar';
import TableGrid from './TableGrid';
import CodePreview from './CodePreview';
import TemplateLibrary from './TemplateLibrary';
import { TableTemplate } from '../utils/templates';

const EditorContainer = styled.div`
  display: flex;
  width: 100%;
  height: 100vh;
  padding: 20px;
  box-sizing: border-box;
`;

const MainContent = styled.div`
  display: flex;
  flex-direction: column;
  flex: 1;
  margin: 0 20px;
  overflow: auto;
`;

const TopBar = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
`;

// 定义单元格默认样式 (保留用于模板功能)
const defaultCellStyle = {
  fontWeight: 'normal',
  fontStyle: 'normal',
  textDecoration: 'none',
  textAlign: 'left',
  backgroundColor: 'transparent',
  color: '#000000',
  borderWidth: '1px',
  borderColor: '#d9d9d9',
  borderStyle: 'solid',
  padding: '8px'
};

const TableEditor: React.FC = () => {
  // 表格数据状态
  const [tableData, setTableData] = useState<{
    rows: number;
    cols: number;
    cells: { 
      rowSpan: number; 
      colSpan: number; 
      content: string;
      style: typeof defaultCellStyle;
    }[][];
  }>({
    rows: 4,
    cols: 4,
    cells: Array(4).fill(0).map(() => 
      Array(4).fill(0).map(() => ({ 
        rowSpan: 1, 
        colSpan: 1, 
        content: '',
        style: {...defaultCellStyle}
      }))
    )
  });
  
  // 当前选中的单元格
  const [selectedCells, setSelectedCells] = useState<{row: number, col: number}[]>([]);
  
  // 模板库抽屉可见性状态
  const [templateLibraryVisible, setTemplateLibraryVisible] = useState(false);
  
  // 处理合并单元格
  const handleMergeCells = (direction: 'row' | 'column') => {
    if (selectedCells.length <= 1) {
      message.warning('请选择至少两个单元格进行合并');
      return;
    }
    
    // 检查选择的单元格是否连续
    if (!checkContinuousCells(selectedCells, direction)) {
      message.error(`所选单元格必须是连续的${direction === 'row' ? '行' : '列'}`);
      return;
    }
    
    // 创建新表格数据的深拷贝
    const newTableData = JSON.parse(JSON.stringify(tableData));
    
    if (direction === 'row') {
      // 合并行
      mergeCellsInRow(newTableData);
    } else {
      // 合并列
      mergeCellsInColumn(newTableData);
    }
    
    setTableData(newTableData);
    // 合并后清空选择
    setSelectedCells([]);
  };
  
  // 检查选中的单元格是否连续
  const checkContinuousCells = (cells: {row: number, col: number}[], direction: 'row' | 'column') => {
    if (cells.length <= 1) return false;
    
    if (direction === 'row') {
      // 所有选中的单元格必须在同一列
      const col = cells[0].col;
      if (!cells.every(cell => cell.col === col)) return false;
      
      // 按行排序
      const sortedRows = cells.map(cell => cell.row).sort((a, b) => a - b);
      
      // 检查是否连续
      for (let i = 1; i < sortedRows.length; i++) {
        if (sortedRows[i] !== sortedRows[i-1] + 1) return false;
      }
    } else {
      // 所有选中的单元格必须在同一行
      const row = cells[0].row;
      if (!cells.every(cell => cell.row === row)) return false;
      
      // 按列排序
      const sortedCols = cells.map(cell => cell.col).sort((a, b) => a - b);
      
      // 检查是否连续
      for (let i = 1; i < sortedCols.length; i++) {
        if (sortedCols[i] !== sortedCols[i-1] + 1) return false;
      }
    }
    
    return true;
  };
  
  // 合并行中的单元格
  const mergeCellsInRow = (data: typeof tableData) => {
    // 所有单元格在同一列
    const col = selectedCells[0].col;
    
    // 排序选中的行
    const sortedCells = [...selectedCells].sort((a, b) => a.row - b.row);
    const firstRow = sortedCells[0].row;
    
    // 设置第一个单元格的rowSpan
    data.cells[firstRow][col].rowSpan = sortedCells.length;
    
    // 收集所有选中单元格的内容
    let mergedContent = data.cells[firstRow][col].content;
    
    // 设置其他单元格为隐藏 (rowSpan = 0)
    for (let i = 1; i < sortedCells.length; i++) {
      const row = sortedCells[i].row;
      
      // 如果有内容，添加到合并内容中
      if (data.cells[row][col].content) {
        mergedContent += " " + data.cells[row][col].content;
      }
      
      // 设置为隐藏
      data.cells[row][col].rowSpan = 0;
      data.cells[row][col].colSpan = 0;
    }
    
    // 更新合并单元格的内容
    data.cells[firstRow][col].content = mergedContent.trim();
  };
  
  // 合并列中的单元格
  const mergeCellsInColumn = (data: typeof tableData) => {
    // 所有单元格在同一行
    const row = selectedCells[0].row;
    
    // 排序选中的列
    const sortedCells = [...selectedCells].sort((a, b) => a.col - b.col);
    const firstCol = sortedCells[0].col;
    
    // 设置第一个单元格的colSpan
    data.cells[row][firstCol].colSpan = sortedCells.length;
    
    // 收集所有选中单元格的内容
    let mergedContent = data.cells[row][firstCol].content;
    
    // 设置其他单元格为隐藏 (colSpan = 0)
    for (let i = 1; i < sortedCells.length; i++) {
      const col = sortedCells[i].col;
      
      // 如果有内容，添加到合并内容中
      if (data.cells[row][col].content) {
        mergedContent += " " + data.cells[row][col].content;
      }
      
      // 设置为隐藏
      data.cells[row][col].rowSpan = 0;
      data.cells[row][col].colSpan = 0;
    }
    
    // 更新合并单元格的内容
    data.cells[row][firstCol].content = mergedContent.trim();
  };
  
  // 添加行
  const addRow = () => {
    const newTableData = {...tableData};
    
    // 添加新行
    newTableData.rows += 1;
    newTableData.cells.push(
      Array(newTableData.cols).fill(0).map(() => ({ 
        rowSpan: 1, 
        colSpan: 1, 
        content: '',
        style: {...defaultCellStyle}
      }))
    );
    
    setTableData(newTableData);
  };
  
  // 添加列
  const addColumn = () => {
    const newTableData = {...tableData};
    
    // 添加新列
    newTableData.cols += 1;
    for (let i = 0; i < newTableData.rows; i++) {
      newTableData.cells[i].push({ 
        rowSpan: 1, 
        colSpan: 1, 
        content: '',
        style: {...defaultCellStyle}
      });
    }
    
    setTableData(newTableData);
  };
  
  // 删除行
  const deleteRow = () => {
    if (tableData.rows <= 1) {
      message.warning('表格至少保留一行');
      return;
    }
    
    if (selectedCells.length === 0) {
      message.warning('请先选择要删除的行');
      return;
    }
    
    // 获取选中的行
    const rowToDelete = selectedCells[0].row;
    
    const newTableData = {...tableData};
    newTableData.rows -= 1;
    newTableData.cells.splice(rowToDelete, 1);
    
    setTableData(newTableData);
    setSelectedCells([]);
  };
  
  // 删除列
  const deleteColumn = () => {
    if (tableData.cols <= 1) {
      message.warning('表格至少保留一列');
      return;
    }
    
    if (selectedCells.length === 0) {
      message.warning('请先选择要删除的列');
      return;
    }
    
    // 获取选中的列
    const colToDelete = selectedCells[0].col;
    
    const newTableData = {...tableData};
    newTableData.cols -= 1;
    
    for (let i = 0; i < newTableData.rows; i++) {
      newTableData.cells[i].splice(colToDelete, 1);
    }
    
    setTableData(newTableData);
    setSelectedCells([]);
  };

  // 打开模板库
  const openTemplateLibrary = () => {
    setTemplateLibraryVisible(true);
  };

  // 处理选择模板
  const handleSelectTemplate = (template: TableTemplate) => {
    // 如果当前表格已有内容，提示确认
    if (hasTableContent()) {
      Modal.confirm({
        title: '应用模板',
        content: '应用模板将会替换当前表格的所有内容，确定要继续吗？',
        okText: '确定',
        cancelText: '取消',
        onOk: () => {
          applyTemplate(template);
        }
      });
    } else {
      applyTemplate(template);
    }
  };

  // 检查表格是否有内容
  const hasTableContent = (): boolean => {
    for (let i = 0; i < tableData.rows; i++) {
      for (let j = 0; j < tableData.cols; j++) {
        if (tableData.cells[i][j].content.trim() !== '') {
          return true;
        }
      }
    }
    return false;
  };

  // 应用模板
  const applyTemplate = (template: TableTemplate) => {
    // 确保所有单元格都有样式属性
    const processedData = {
      ...template.data,
      cells: template.data.cells.map(row => 
        row.map(cell => ({
          ...cell,
          style: cell.style || {...defaultCellStyle}  // 确保每个单元格都有样式
        }))
      )
    };
    
    setTableData(processedData);
    setSelectedCells([]);
  };

  return (
    <EditorContainer>
      {/* 左侧工具栏 */}
      <ToolBar 
        onMerge={handleMergeCells}
        onAddRow={addRow}
        onAddColumn={addColumn}
        onDeleteRow={deleteRow}
        onDeleteColumn={deleteColumn}
      />
      
      <MainContent>
        <TopBar>
          <h2>表格编辑器</h2>
          <Button 
            type="primary" 
            icon={<BookOutlined />} 
            onClick={openTemplateLibrary}
          >
            模板库
          </Button>
        </TopBar>

        {/* 中间表格区域 */}
        <TableGrid 
          tableData={tableData} 
          selectedCells={selectedCells}
          onSelectCells={setSelectedCells}
          onUpdateCell={(row: number, col: number, value: string) => {
            const newData = {...tableData};
            newData.cells[row][col].content = value;
            setTableData(newData);
          }}
        />
      </MainContent>
      
      {/* 右侧代码预览 */}
      <CodePreview tableData={tableData} />

      {/* 模板库抽屉 */}
      <Drawer
        title="表格模板库"
        placement="right"
        width={800}
        visible={templateLibraryVisible}
        onClose={() => setTemplateLibraryVisible(false)}
        destroyOnClose
      >
        <TemplateLibrary
          onSelectTemplate={handleSelectTemplate}
          currentTableData={tableData}
          onClose={() => setTemplateLibraryVisible(false)}
        />
      </Drawer>
    </EditorContainer>
  );
};

export default TableEditor; 